#include <stdio.h>
#include <wiringPi.h>
#include <pthread.h>
#include <unistd.h>
#define dht 2      //引脚接口 wpi序号
unsigned long databuf;  //温湿度数据保存区
 
int readSensorData(void) //温湿度初始化
{
    char i;
 
    pinMode(dht, OUTPUT);   // 将模式设置为输出
    digitalWrite(dht, LOW); // 输出高电平
    delay(25);
    digitalWrite(dht, HIGH); // 输出低电平
    pinMode(dht, INPUT);     // 将模式设置为输入
    pullUpDnControl(dht, PUD_UP);
 
    delayMicroseconds(27);
    if (digitalRead(dht) == 0){
 
        while (!digitalRead(dht)); // wait to high
 
        for (i = 0; i < 32; i++)
        {
            while (digitalRead(dht)); // 数据时钟启动
            while (!digitalRead(dht)); //数据开始
            delayMicroseconds(40);
            databuf *= 2;
            if (digitalRead(dht) == 1) // 1
            {
                    databuf++;
            }
        }
 
        return 1;
    }else
    {
        return 0;
    }
 
}
 
void *dht11_thread(void *datas) //温湿度线程
{
    int W = 0, w = 0;
    int S = 0, s = 0;
    printf("Use GPIO7 wpi2 to read data!\n");
 
 
    pinMode(dht, OUTPUT);    // set mode to output
    digitalWrite(dht, HIGH); // output a high level
 
    printf("Enter OS-------\n");
    while (1)
    {
        if (readSensorData())
        {
 
            W = (databuf >> 8) & 0xff;
            w = databuf & 0xff;
            S = (databuf >> 24) & 0xff;
            s = (databuf >> 16) & 0xff;
        }
        delay(2000);
        if ((W >= 15) && (W <= 35) && (S <= 85) && (S>=15))
         {
                printf("此时的温湿度为：\n");
                printf("温度：%d.%d\n", W, w); //温度
                printf( "湿度：%d.%d\n", S, s);   //湿度
                databuf = 0;
         }else{
            printf("Sorry! Sensor dosent ans!\n");
            databuf = 0;
            continue;
        }
 
    }
}
 
int main()
{
        int ret;
        pthread_t dht11Thread;
 
        if (-1 == wiringPiSetup())
        {
                printf("Setup wiringPi failed!");
        }
 
        ret = pthread_create(&dht11Thread,NULL,dht11_thread,NULL);//启动线程不断获取温湿度数据
 
        if(ret == 0){
                printf("dht11Thread create success!\n");
        }
 
        pthread_join(dht11Thread,NULL);//等待线程退出
 
        return 0;
}